<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>空气质量趋势分析 | WeatherViz Pro</title>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap');

        :root {
            --primary-color: #3498db; /* 柔和蓝色 */
            --secondary-color: #2ecc71; /* 温和绿色 */
            --accent-color: #e74c3c; /* 低调红色 */
            --dark-bg: #f5f7fa; /* 浅灰色背景 */
            --light-text: #333333; /* 深灰色文字 */
            --medium-text: #555555; /* 中灰色文字 */
            --light-gray: #9ca3af; /* 浅灰色文字 */
            --shadow-color: rgba(0, 0, 0, 0.1);
            --glass-bg: rgba(255, 255, 255, 0.95); /* 半透明白色面板 */

            --shadow-depth: 0 2px 10px var(--shadow-color);
            --aqi-excellent: rgba(0, 228, 0, 0.1);
            --aqi-good: rgba(255, 255, 0, 0.1);
            --aqi-light-pollution: rgba(255, 126, 0, 0.1);
            --aqi-moderate-pollution: rgba(255, 0, 0, 0.1);
            --aqi-heavy-pollution: rgba(153, 0, 76, 0.1);
            --aqi-severe-pollution: rgba(126, 0, 35, 0.1);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Noto Sans SC', sans-serif;
            scroll-behavior: smooth;
            transition: all 0.3s ease;
        }

        body {
            background: var(--dark-bg);
            color: var(--light-text);
            line-height: 1.6;
            overflow-x: hidden;
            background-image: none;
        }

        .container {
            width: 95%;
            max-width: 1200px;
            margin: 30px auto;
            padding: 20px;
        }

        h2 {
            text-align: center;
            color: var(--primary-color);
            font-size: 1.8rem;
            margin-bottom: 1.5rem;
            padding: 0.5rem 0;
            position: relative;
        }

        h2::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 80px;
            height: 2px;
            background: var(--primary-color);
        }

        .glass-panel {
            background: var(--glass-bg);
            border-radius: 12px;
            box-shadow: var(--shadow-depth);
            padding: 1.5rem;
            margin-bottom: 2rem;
            border: 1px solid #eaeaea;
        }

        .controls {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            margin-bottom: 1.5rem;
            align-items: center;
        }

        select {
            padding: 0.6rem 1.2rem;
            background: #ffffff;
            color: var(--light-text);
            border: 1px solid #ddd;
            border-radius: 6px;
            outline: none;
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%233498db'%3E%3Cpath d='M7 10l5 5 5-5z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 12px center;
            background-size: 12px;
            font-size: 0.95rem;
            transition: all 0.3s ease;
        }

        select:hover {
            border-color: var(--primary-color);
        }

        select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }

        label {
            color: var(--medium-text);
            font-size: 0.9rem;
            margin-right: 0.5rem;
        }

        #airQualityChart {
            width: 100%;
            height: 480px;
            border-radius: 8px;
            background: #ffffff;
            border: 1px solid #eaeaea;
            box-shadow: 0 1px 3px var(--shadow-color);
            margin-bottom: 15px;
        }

        .return-button {
            position: absolute;
            top: 20px;
            right: 20px;
            background: #f0f2f5;
            color: #4b5563;
            padding: 0.6rem 1.2rem;
            border-radius: 6px;
            border: 1px solid #ddd;
            text-decoration: none;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            font-size: 0.95rem;
        }

        .return-button:hover {
            background: #e5e7eb;
            color: #374151;
            transform: translateY(-1px);
            box-shadow: 0 1px 3px var(--shadow-color);
        }

        .return-button i {
            margin-right: 0.4rem;
        }

        .info-section {
            margin-bottom: 1.5rem;
            padding: 1rem;
            background-color: #f8fafc;
            border-left: 3px solid var(--primary-color);
            border-radius: 0 4px 4px 0;
        }

        .info-title {
            color: var(--primary-color);
            font-weight: 500;
            margin-bottom: 0.5rem;
            display: flex;
            align-items: center;
        }

        .info-title i {
            margin-right: 0.5rem;
        }

        .info-content {
            color: var(--medium-text);
            font-size: 0.95rem;
            line-height: 1.7;
        }

        .aqi-levels {
            display: flex;
            flex-wrap: wrap;
            gap: 0.8rem;
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 1px dashed #e2e8f0;
        }

        .aqi-level {
            display: flex;
            align-items: center;
            font-size: 0.85rem;
        }

        .level-color {
            width: 12px;
            height: 12px;
            border-radius: 2px;
            margin-right: 0.5rem;
        }

        .data-note {
            font-size: 0.85rem;
            color: var(--light-gray);
            margin-top: 1rem;
            font-style: italic;
        }
    </style>
</head>

<body>
    <div class="container">
        <h2>空气质量趋势分析</h2>

        <div class="info-section">
            <div class="info-title">
                <i class="fas fa-info-circle"></i> 数据说明
            </div>
            <div class="info-content">
                <p>本页面展示各城市月度平均空气质量指数(AQI)趋势。AQI是衡量空气质量的关键指标，数值越高表示污染越严重，对人体健康的影响越大。</p>
                <p>您可以通过上方控件选择不同城市和年份，查看单一年度的月度趋势或多年历史对比。图表中不同颜色区域代表不同空气质量等级，具体划分如下：</p>
                <div class="aqi-levels">
                    <div class="aqi-level">
                        <div class="level-color" style="background-color: #00E400;"></div>
                        <span>优 (0-50)：空气质量令人满意，基本无空气污染</span>
                    </div>
                    <div class="aqi-level">
                        <div class="level-color" style="background-color: #FFFF00;"></div>
                        <span>良 (51-100)：空气质量可接受，极少数敏感人群可能有轻微症状</span>
                    </div>
                    <div class="aqi-level">
                        <div class="level-color" style="background-color: #FF7E00;"></div>
                        <span>轻度污染 (101-150)：敏感人群症状可能加剧，健康人群出现刺激症状</span>
                    </div>
                    <div class="aqi-level">
                        <div class="level-color" style="background-color: #FF0000;"></div>
                        <span>中度污染 (151-200)：一定程度上普遍人群健康会受到影响</span>
                    </div>
                    <div class="aqi-level">
                        <div class="level-color" style="background-color: #99004C;"></div>
                        <span>重度污染 (201-300)：健康人群明显感觉不适，运动耐受力降低</span>
                    </div>
                    <div class="aqi-level">
                        <div class="level-color" style="background-color: #7E0023;"></div>
                        <span>严重污染 (300+)：健康人群健康将受到严重影响，应避免户外活动</span>
                    </div>
                </div>
                <p class="data-note">注：数据为各城市国控监测点的月度平均值，可能存在轻微统计误差。历史数据最早可追溯至2015年，部分城市早期数据可能存在缺失。</p>
            </div>
        </div>

        <div class="glass-panel">
            <div class="controls">
                <div>
                    <label for="citySelect">城市：</label>
                    <select id="citySelect">
                        {% for city in cities %}
                            <option value="{{ city }}" {% if city == urban %}selected{% endif %}>{{ city }}</option>
                        {% endfor %}
                    </select>
                </div>

                <div>
                    <label for="yearSelect">年份：</label>
                    <select id="yearSelect">
                        <option value="">全部年份</option>
                        {% for year in years %}
                            <option value="{{ year }}">{{ year }} 年</option>
                        {% endfor %}
                    </select>
                </div>
            </div>

            <div id="airQualityChart"></div>
        </div>



        <script>
            // 自定义ECharts主题 - 朴素风格
            const simpleTheme = {
                color: [
                    '#3498db', '#2ecc71', '#e74c3c',
                    '#9b59b6', '#34495e', '#27ae60',
                    '#f39c12', '#e74c3c', '#7f8c8d'
                ],
                backgroundColor: '#ffffff',
                textStyle: {
                    color: '#333333'
                },
                title: {
                    textStyle: {
                        color: '#3498db',
                        fontWeight: 'normal',
                        fontFamily: 'Noto Sans SC, sans-serif',
                        fontSize: 16,
                        textShadow: 'none'
                    }
                },
                tooltip: {
                    backgroundColor: 'rgba(255, 255, 255, 0.95)',
                    borderColor: '#eaeaea',
                    borderWidth: 1,
                    textStyle: {
                        color: '#333333'
                    },
                    axisPointer: {
                        lineStyle: {
                            color: '#3498db',
                            width: 1,
                            type: 'dashed'
                        }
                    }
                },
                legend: {
                    textStyle: {
                        color: '#555555'
                    }
                },
                xAxis: {
                    axisLine: {
                        lineStyle: {
                            color: '#eaeaea'
                        }
                    },
                    axisTick: {
                        lineStyle: {
                            color: '#eaeaea'
                        }
                    },
                    axisLabel: {
                        textStyle: {
                            color: '#555555'
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            color: '#f0f0f0'
                        }
                    }
                },
                yAxis: {
                    axisLine: {
                        lineStyle: {
                            color: '#eaeaea'
                        }
                    },
                    axisTick: {
                        lineStyle: {
                            color: '#eaeaea'
                        }
                    },
                    axisLabel: {
                        textStyle: {
                            color: '#555555'
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            color: '#f0f0f0'
                        }
                    }
                },
                grid: {
                    borderColor: '#f0f0f0'
                },
                line: {
                    itemStyle: {
                        borderWidth: 2
                    },
                    lineStyle: {
                        width: 2,
                        shadowBlur: 0,
                        shadowColor: 'transparent'
                    },
                    emphasis: {
                        lineStyle: {
                            width: 3
                        }
                    }
                },
                dataZoom: {
                    handleStyle: {
                        color: '#3498db',
                        borderColor: '#ddd'
                    },
                    textStyle: {
                        color: '#555555'
                    }
                }
            };

            // 注册自定义主题
            echarts.registerTheme('simple', simpleTheme);

            const airQualityChartDom = document.getElementById('airQualityChart');
            const airQualityChart = echarts.init(airQualityChartDom, 'simple');

            // 存储所有年份的数据缓存
            let allYearsAirQualityData = {};

            function updateCharts(city, year) {
                // 空气质量趋势图
                updateAirQualityChart(city, year);
            }

            function updateAirQualityChart(city, year) {
                // 如果已经缓存了该城市的所有年份数据，并且当前请求全部年份，则直接使用缓存
                if (year === "" && allYearsAirQualityData[city]) {
                    renderAllYearsAirQualityChart(city);
                    return;
                }

                let url = `/menu/monthly_air_quality?urban=${encodeURIComponent(city)}`;
                if (year) {
                    url += `&year=${encodeURIComponent(year)}`;
                }

                console.log('Fetching data from:', url);

                fetch(url)
                   .then(response => {
                        if (!response.ok) {
                            throw new Error('Network response was not ok');
                        }
                        return response.json();
                    })
                   .then(data => {
                        if (data.error) {
                            alert(data.error);
                            return;
                        }

                        // 如果是获取全部年份数据，缓存起来
                        if (year === "") {
                            // 处理全部年份数据，将其格式化为更易处理的结构
                            const formattedData = formatAllYearsAirQualityData(data);
                            allYearsAirQualityData[city] = formattedData;
                            renderAllYearsAirQualityChart(city);
                        } else {
                            // 处理单一年份数据
                            const seriesData = data.months.map((month, index) => ({
                                name: month,
                                value: data.aqi[index]  // 使用aqi作为数据键名
                            }));

                            // 根据AQI值设置不同的颜色
                            const aqiColors = [
                                '#00E400', // 优 (0-50)
                                '#FFFF00', // 良 (51-100)
                                '#FF7E00', // 轻度污染 (101-150)
                                '#FF0000', // 中度污染 (151-200)
                                '#99004C', // 重度污染 (201-300)
                                '#7E0023'  // 严重污染 (300+)
                            ];

                            // 为不同AQI级别创建渐变颜色（简化版）
                            const getAQIGradient = (aqiValue) => {
                                let colorIndex = Math.min(Math.floor(aqiValue / 50), aqiColors.length - 1);
                                return {
                                    type: 'linear',
                                    x: 0, y: 0, x2: 0, y2: 1,
                                    colorStops: [{
                                        offset: 0, color: `${aqiColors[colorIndex]}1A` // 透明度10%
                                    }, {
                                        offset: 1, color: 'transparent'
                                    }],
                                    global: false
                                };
                            };

                            // 计算AQI范围，用于确定默认Y轴范围
                            const aqiMin = Math.min(...data.aqi) || 0;
                            const aqiMax = Math.max(...data.aqi) || 100;
                            const yAxisMax = Math.max(100, Math.ceil(aqiMax / 50) * 50); // 确保Y轴最大值是50的倍数且至少为100

                            const option = {
                                title: {
                                    text: `${city} ${year} 年月度平均空气质量趋势`,
                                    left: 'center'
                                },
                                tooltip: {
                                    trigger: 'axis',
                                    backgroundColor: 'rgba(255, 255, 255, 0.95)',
                                    borderColor: '#eaeaea',
                                    borderWidth: 1,
                                    textStyle: {
                                        color: '#333333'
                                    },
                                    axisPointer: {
                                        type: 'line',
                                        lineStyle: {
                                            color: '#3498db',
                                            width: 1,
                                            opacity: 0.8
                                        }
                                    },
                                    formatter: function (params) {
                                        const param = params[0];
                                        const aqiValue = param.value;
                                        let aqiLevel = '';
                                        let levelColor = '';

                                        if (aqiValue <= 50) {
                                            aqiLevel = '优';
                                            levelColor = '#00E400';
                                        } else if (aqiValue <= 100) {
                                            aqiLevel = '良';
                                            levelColor = '#FFFF00';
                                        } else if (aqiValue <= 150) {
                                            aqiLevel = '轻度污染';
                                            levelColor = '#FF7E00';
                                        } else if (aqiValue <= 200) {
                                            aqiLevel = '中度污染';
                                            levelColor = '#FF0000';
                                        } else if (aqiValue <= 300) {
                                            aqiLevel = '重度污染';
                                            levelColor = '#99004C';
                                        } else {
                                            aqiLevel = '严重污染';
                                            levelColor = '#7E0023';
                                        }

                                        return `
                                            <div style="margin-bottom:5px;font-weight:500;">${param.name}</div>
                                            <div>${param.marker} AQI: ${aqiValue.toFixed(1)}</div>
                                            <div style="color:${levelColor}">空气质量等级: ${aqiLevel}</div>
                                        `;
                                    }
                                },
                                xAxis: {
                                    type: 'category',
                                    data: data.months.map(m => m.split('-')[1] + '月'), // 只显示月份
                                    axisLine: {
                                        lineStyle: {
                                            color: '#eaeaea'
                                        }
                                    },
                                    axisTick: {
                                        lineStyle: {
                                            color: '#eaeaea'
                                        }
                                    },
                                    axisLabel: {
                                        textStyle: {
                                            color: '#555555'
                                        }
                                    }
                                },
                                yAxis: {
                                    type: 'value',
                                    name: '空气质量指数 (AQI)',
                                    nameTextStyle: {
                                        color: '#555555'
                                    },
                                    min: 0,
                                    max: yAxisMax,
                                    axisLine: {
                                        lineStyle: {
                                            color: '#eaeaea'
                                        }
                                    },
                                    axisTick: {
                                        lineStyle: {
                                            color: '#eaeaea'
                                        }
                                    },
                                    axisLabel: {
                                        textStyle: {
                                            color: '#555555'
                                        }
                                    },
                                    splitLine: {
                                        lineStyle: {
                                            color: '#f0f0f0'
                                        }
                                    },
                                    // 添加AQI等级背景色带（简化样式）
                                    splitArea: {
                                        show: true,
                                        areas: [
                                            {name: '优', value: 50, color: getComputedStyle(document.documentElement).getPropertyValue('--aqi-excellent').trim()},
                                            {name: '良', value: 100, color: getComputedStyle(document.documentElement).getPropertyValue('--aqi-good').trim()},
                                            {name: '轻度污染', value: 150, color: getComputedStyle(document.documentElement).getPropertyValue('--aqi-light-pollution').trim()},
                                            {name: '中度污染', value: 200, color: getComputedStyle(document.documentElement).getPropertyValue('--aqi-moderate-pollution').trim()},
                                            {name: '重度污染', value: 300, color: getComputedStyle(document.documentElement).getPropertyValue('--aqi-heavy-pollution').trim()},
                                            {name: '严重污染', value: 500, color: getComputedStyle(document.documentElement).getPropertyValue('--aqi-severe-pollution').trim()}
                                        ].map((area, index) => ({
                                            interval: 0,
                                            start: index === 0? 0 : area.value - 50,
                                            end: area.value,
                                            color: area.color
                                        }))
                                    }
                                },
                                series: [{
                                    name: `${year}年`,
                                    type: 'line',
                                    data: seriesData,
                                    showSymbol: true,
                                    symbol: 'circle',
                                    symbolSize: 6,
                                    itemStyle: {
                                        color: function(params) {
                                            const aqiValue = params.data.value;
                                            let colorIndex = Math.min(Math.floor(aqiValue / 50), aqiColors.length - 1);
                                            return aqiColors[colorIndex];
                                        },
                                        borderWidth: 1,
                                        borderColor: '#ffffff'
                                    },
                                    lineStyle: {
                                        width: 2,
                                        shadowBlur: 0,
                                        shadowColor: 'transparent'
                                    },
                                    areaStyle: {
                                        color: function(params) {
                                            const aqiValue = params.data.value;
                                            return getAQIGradient(aqiValue);
                                        }
                                    }
                                }]
                            };

                            airQualityChart.setOption(option, true);
                        }
                    })
                   .catch(error => {
                        console.error('Error fetching air quality data:', error);
                        alert('获取空气质量数据失败，请重试');
                    });
            }

            // 格式化全部年份的空气质量数据
            function formatAllYearsAirQualityData(data) {
                const yearsData = {};

                data.months.forEach((monthStr, index) => {
                    const [year, month] = monthStr.split('-');
                    const aqi = data.aqi[index];  // 使用aqi作为数据键名

                    if (!yearsData[year]) {
                        yearsData[year] = Array(12).fill(null);
                    }

                    const monthIndex = parseInt(month) - 1;
                    yearsData[year][monthIndex] = aqi;
                });

                return yearsData;
            }

            // 渲染所有年份空气质量数据的图表
            function renderAllYearsAirQualityChart(city) {
                const yearsData = allYearsAirQualityData[city];
                if (!yearsData) {
                    return;
                }

                // 创建年份排序数组
                const sortedYears = Object.keys(yearsData)
                   .map(y => parseInt(y))
                   .sort((a, b) => a - b);

                // 创建系列数据
                const series = sortedYears.map((year, index) => ({
                    name: `${year}年`,
                    type: 'line',
                    data: yearsData[year].map(v => v === -1? null : v),
                    showSymbol: true,
                    symbol: 'circle',
                    symbolSize: 5,
                    smooth: true,
                    lineStyle: {
                        width: 2,
                        shadowBlur: 0,
                        shadowColor: 'transparent'
                    },
                    areaStyle: {
                        opacity: 0.05
                    },
                    connectNulls: true,
                    emphasis: {
                        focus:'series',
                        scale: true,
                        itemStyle: {
                            borderWidth: 2
                        }
                    }
                }));

                // X轴月份标签（中文格式）
                const xAxisData = Array.from({ length: 12 }, (_, i) => `${i + 1}月`);

                // 计算所有年份的AQI范围
                const allAqiValues = [];
                for (const year in yearsData) {
                    yearsData[year].forEach(aqi => {
                        if (aqi !== null) allAqiValues.push(aqi);
                    });
                }
                const aqiMin = Math.min(...allAqiValues) || 0;
                const aqiMax = Math.max(...allAqiValues) || 100;
                const yAxisMax = Math.max(100, Math.ceil(aqiMax / 50) * 50); // 确保Y轴最大值是50的倍数且至少为100

                const option = {
                    title: {
                        text: `${city} 月度平均空气质量历史趋势`,
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis',
                        backgroundColor: 'rgba(255, 255, 255, 0.95)',
                        borderColor: '#eaeaea',
                        borderWidth: 1,
                        textStyle: {
                            color: '#333333'
                        },
                        axisPointer: {
                            type: 'cross',
                            lineStyle: {
                                color: '#3498db',
                                width: 1,
                                opacity: 0.8
                            }
                        },
                        formatter: function (params) {
                            let tooltip = `<b>${params[0].name}</b><br>`;
                            params.forEach(p => {
                                if (p.value !== null) {
                                    const aqiValue = p.value;
                                    let aqiLevel = '';
                                    let levelColor = '';

                                    if (aqiValue <= 50) {
                                        aqiLevel = '优';
                                        levelColor = '#00E400';
                                    } else if (aqiValue <= 100) {
                                        aqiLevel = '良';
                                        levelColor = '#FFFF00';
                                    } else if (aqiValue <= 150) {
                                        aqiLevel = '轻度污染';
                                        levelColor = '#FF7E00';
                                    } else if (aqiValue <= 200) {
                                        aqiLevel = '中度污染';
                                        levelColor = '#FF0000';
                                    } else if (aqiValue <= 300) {
                                        aqiLevel = '重度污染';
                                        levelColor = '#99004C';
                                    } else {
                                        aqiLevel = '严重污染';
                                        levelColor = '#7E0023';
                                    }

                                    tooltip += `${p.marker} ${p.seriesName}: ${aqiValue.toFixed(1)} (${aqiLevel})<br>`;
                                }
                            });
                            return tooltip;
                        }
                    },
                    legend: {
                        type: 'scroll',
                        bottom: 10,
                        pageIconColor: '#3498db',
                        pageTextStyle: {
                            color: '#555555',
                            fontFamily: 'Noto Sans SC, sans-serif'
                        },
                        textStyle: {
                            color: '#555555',
                            fontFamily: 'Noto Sans SC, sans-serif'
                        }
                    },
                    xAxis: {
                        type: 'category',
                        data: xAxisData,
                        axisTick: { alignWithLabel: true },
                        axisLine: {
                            lineStyle: {
                                color: '#eaeaea'
                            }
                        },
                        axisLabel: {
                            textStyle: {
                                color: '#555555'
                            }
                        },
                        splitLine: {
                            lineStyle: {
                                color: '#f0f0f0'
                            }
                        }
                    },
                    yAxis: {
                        type: 'value',
                        name: '空气质量指数 (AQI)',
                        nameTextStyle: {
                            color: '#555555'
                        },
                        min: 0,
                        max: yAxisMax,
                        axisLine: {
                            lineStyle: {
                                color: '#eaeaea'
                            }
                        },
                        axisTick: {
                            lineStyle: {
                                color: '#eaeaea'
                            }
                        },
                        axisLabel: {
                            textStyle: {
                                color: '#555555'
                            }
                        },
                        splitLine: {
                            lineStyle: {
                                color: '#f0f0f0'
                            }
                        },
                        // 添加AQI等级背景色带
                        splitArea: {
                            show: true,
                            areas: [
                                {name: '优', value: 50, color: getComputedStyle(document.documentElement).getPropertyValue('--aqi-excellent').trim()},
                                {name: '良', value: 100, color: getComputedStyle(document.documentElement).getPropertyValue('--aqi-good').trim()},
                                {name: '轻度污染', value: 150, color: getComputedStyle(document.documentElement).getPropertyValue('--aqi-light-pollution').trim()},
                                {name: '中度污染', value: 200, color: getComputedStyle(document.documentElement).getPropertyValue('--aqi-moderate-pollution').trim()},
                                {name: '重度污染', value: 300, color: getComputedStyle(document.documentElement).getPropertyValue('--aqi-heavy-pollution').trim()},
                                {name: '严重污染', value: 500, color: getComputedStyle(document.documentElement).getPropertyValue('--aqi-severe-pollution').trim()}
                            ].map((area, index) => ({
                                interval: 0,
                                start: index === 0? 0 : area.value - 50,
                                end: area.value,
                                color: area.color
                            }))
                        }
                    },
                    dataZoom: [{
                        type:'slider',
                        show: true,
                        height: 16,
                        bottom: 40,
                        start: 0,
                        end: 100,
                        handleStyle: {
                            color: '#3498db',
                            borderColor: '#ddd'
                        },
                        textStyle: {
                            color: '#555555'
                        },
                        backgroundColor: '#f0f0f0',
                        fillerColor: 'rgba(52, 152, 219, 0.15)'
                    }],
                    series: series,
                    grid: {
                        top: 70,
                        bottom: 100,
                        containLabel: true
                    }
                };

                airQualityChart.setOption(option, true);
            }

            const citySelect = document.getElementById('citySelect');
            const yearSelect = document.getElementById('yearSelect');

            citySelect.addEventListener('change', () => {
                // 切换城市时清除缓存
                allYearsAirQualityData = {};
                const selectedCity = citySelect.value;
                const selectedYear = yearSelect.value;
                console.log('City changed to:', selectedCity, 'Year:', selectedYear);
                updateCharts(selectedCity, selectedYear);
            });

            yearSelect.addEventListener('change', () => {
                const selectedCity = citySelect.value;
                const selectedYear = yearSelect.value;
                console.log('Year changed to:', selectedYear, 'City:', selectedCity);
                updateCharts(selectedCity, selectedYear);
            });

            // 初始化图表
            const initialCity = "{{ urban }}";
            const initialYear = ""; // 默认显示全部年份
            updateCharts(initialCity, initialYear);

            // 监听窗口大小变化，调整图表尺寸
            window.addEventListener('resize', () => {
                airQualityChart.resize();
            });
        </script>
    </div>
</body>

</html>